package com.learn.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.UUID;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/02/06
 * @description
 */
@RestController
public class FileController {
    @PostMapping("/upload")
    public String upload(@RequestParam("fileName") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        // 获取请求参数的名字 fileName
        String name = multipartFile.getName();
        // 获取文件的真实名字 P1757_1.in
        String originalFilename = multipartFile.getOriginalFilename();
        // 获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        ServletContext application = request.getServletContext();
        // 获取类根目录的绝对路径，以存放文件
        String realPath = application.getRealPath("/upload");
        // D:\Codes\Java\springmvc\ch09-file\target\ch09-file-1.0-SNAPSHOT\ upload

        File dir = new File(realPath);
        // 如果目录不存在，则新建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 目标文件，使用uuid可以避免同名覆盖
        String realName = UUID.randomUUID().toString().replace("-", "") + suffix;
        File destFile = new File(realPath + "/" + realName);


        // 边读边写，创建输入输出流
        InputStream in = multipartFile.getInputStream();
        // 封装成BufferedInputStream，提高效率
        BufferedInputStream bin = new BufferedInputStream(in);
        // 输出流, 需要提供保存路径
        BufferedOutputStream bon = new BufferedOutputStream(new FileOutputStream(destFile));
        // 边读边写
        byte[] bytes = new byte[bin.available()];
        // 为文件的字节数
        int readCount = 0;
        while ((readCount = bin.read(bytes)) != -1) {
            bon.write(bytes, 0, readCount);
        }

        bon.flush();
        bon.close();
        bin.close();
        in.close();
        // 也可以直接使用这个方法
        // multipartFile.transferTo(destFile);
        return "ok";
    }
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
        File file = new File(request.getServletContext().getRealPath("/upload") + "/Weixin Image_20250107224536.png");
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 设置响应类型
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 设置文件名，直接显示，还是将其作为附件下载
        headers.setContentDispositionFormData("attachment", file.getName());
        return new ResponseEntity<>(Files.readAllBytes(file.toPath()), headers, HttpStatus.OK);
    }
}
